package com.maruti.otterapi.linkposts;

import com.maruti.otterapi.ListParameters;
import com.maruti.otterapi.Otter4JavaException;
import com.maruti.otterapi.TopsyConfig;
import com.maruti.otterapi.TopsyConstants;
import com.maruti.otterapi.TopsyInvoker;
import com.maruti.otterapi.search.SearchCriteria;
import com.maruti.otterapi.search.SearchResponse;

public class Linkposts {

	private TopsyConfig topsyConfig;

	public TopsyConfig getTopsyConfig() {
		return topsyConfig;
	}

	public void setTopsyConfig(TopsyConfig topsyConfig) {
		this.topsyConfig = topsyConfig;
	}

	public LinkpostsResponse linkposts(LinkpostsRequest request)
			throws Otter4JavaException {

		if (request.getListParams() == null
				|| request.getListParams().getPage() == null)
			return fetchAll(request, "search");
		return fetch(request, "search");
	}

	public LinkpostsResponse linkpostsCount(LinkpostsRequest request)
			throws Otter4JavaException {

		return fetch(request, "count");
	}

	private LinkpostsResponse fetchAll(LinkpostsRequest request, String type)
			throws Otter4JavaException {

		int page = 1;
		ListParameters listParameters = null;
		if (request.getListParams() != null)
			listParameters = request.getListParams();
		else
			listParameters = new ListParameters();
		listParameters.setPage("" + page);
		listParameters.setPerpage("100");
		request.setListParams(listParameters);
		LinkpostsResponse response = fetch(request, type);
		int total = Integer.parseInt(response.getResponse().getTotal());
		int fetchedRecs = response.getResponse().getList().size();
		LinkpostsResponse response1 = null;
		String lastOffset = response.getResponse().getLast_offset();
		page++;
		while (total > fetchedRecs && page <= 10) {
			listParameters.setPage("" + page);
			// listParameters.setOffset(lastOffset);
			response1 = fetch(request, type);
			response.getResponse().getList().addAll(
					response1.getResponse().getList());
			fetchedRecs += response1.getResponse().getList().size();
			System.out.println(response1.getResponse().getList().size());
			lastOffset = response1.getResponse().getLast_offset();
			page++;
		}

		return response;
	}

	private LinkpostsResponse fetch(LinkpostsRequest request, String type)
			throws Otter4JavaException {
		TopsyInvoker invoker = new TopsyInvoker();
		invoker.setTopsyConfig(topsyConfig);

		String query = request.toQuery();
		String url = TopsyConstants.linkpostsURL;
		if ("count".equalsIgnoreCase(type))
			url = TopsyConstants.linkpostsCountURL;

		LinkpostsResponse data = (LinkpostsResponse) invoker.fetchData(url
				+ query, "linkposts");

		return data;
	}
}
